package com.centling.task;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.centling.business.OfflinemeasureVO;
import com.centling.controller.CustomerController;
import com.centling.service.IOfflinemeasureService;
import com.centling.util.DateUtils;
import com.centling.util.Encryption;

@Component
@Transactional
public class OfflinemeasureInfoImportTasks {

	private static Logger log = Logger.getLogger(OfflinemeasureInfoImportTasks.class);

	@Resource
	protected IOfflinemeasureService offlinemeasureService;
	
	@Value("${task.offlinemeasure.import.post_url}")
	private String post_url;
	
	@Value("${task.offlinemeasure.import.num}")
	private String num;
	
	@Value("${task.offlinemeasure.import.daynum}")
	private Integer daynum;
	
	/**
	 * This task will be performed every 30 minutes
	 * @throws Exception 
	 */
	@Scheduled(cron = "0 0/${task.offlinemeasure.import.mintus} * * * *")
	@Transactional
	private void offlinemeasureInfoImportCRM() throws Exception {
		/*log.info("Performing Scheduled task: offlinemeasures Import CRM");
		String beginTime	= DateUtils.addDay(DateUtils.getCurrDate(), daynum)+" 00:00:00";
		String endTime		= DateUtils.getCurrDate()+" 23:59:59";
		log.info("offlinemeasure info request BeginTime:	"+beginTime);
		log.info("offlinemeasure info request endTime  :	"+endTime);
		log.info("offlinemeasure info request num      :	"+num);
		
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("beginTime", beginTime);
		paramMap.put("endTime", endTime);
		paramMap.put("num", num);
		
		// Post请求的url，与get不同的是不需要带参数
        URL postUrl = new URL(post_url);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection
                .getOutputStream());
    	
    	String str = JSON.toJSONString(paramMap);
    	
    	String mi = Encryption.encrypt(str, "RCCRMKEY");
    	log.info("mi: "+mi);
        
        // The URL-encoded contend
        // 正文，正文内容其实跟get的URL中'?'后的参数字符串一致
        String content = "encryptionJsonStr=" + URLEncoder.encode(mi, "utf-8");
        // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
        out.writeBytes(content); 

        out.flush();
        out.close(); // flush and close
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        StringBuffer sb = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        connection.disconnect();
        
        String jsonStr=Encryption.decrypt(sb.toString(), CustomerController.RC_CRM_KEY); 
		log.info("param after: " + jsonStr);
		JSONArray jsonArr = JSON.parseArray(jsonStr);
		List<OfflinemeasureVO> list = new ArrayList<OfflinemeasureVO>();
		for (int i=0; i<jsonArr.size(); i++){
			OfflinemeasureVO vo = JSON.toJavaObject(jsonArr.getJSONObject(i), OfflinemeasureVO.class);
			list.add(vo);
		}
		Boolean returnVal = offlinemeasureService.save(list);
		log.info("Performing Scheduled task: offlinemeasures Import CRM end..., with return " + returnVal);*/
	}
}
